<template>
  <div style="margin: 10px">
    <el-button type="primary" :icon="Plus" @click="openDialog(false)">新增</el-button>
  </div>
  <el-card>
    <el-table :data="tableData" border stripe style="width: 100%">
      <el-table-column prop="roleId" label="ID" />
      <el-table-column prop="roleName" label="角色名"/>
      <el-table-column label="操作">
        <template #default="{row}">
          <el-button @click="openDialog(true, row)" size="small" type="primary">编辑</el-button>
          <el-button @click="handleRemove(row.roleId)" size="small" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <el-dialog v-model="editAddRoleFlag" :title="isEdit ? '修改角色': '创建角色'" @close="editAddRoleFlag=false" @closed="resetData" destroy-on-close center>
    <el-form :model="roleForm">
      <el-form-item label="Id" prop="roleId">
        <el-input type="number" v-model="roleForm.roleId" autocomplete="off" disabled/>
      </el-form-item>
      <el-form-item label="角色名" prop="roleName">
        <el-input  v-model="roleForm.roleName" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="editAddRoleFlag=false">关闭</el-button>
      <el-button type="primary" @click="handleDialogSubmit">提交</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">


import {onMounted, ref} from "vue";
import {addRole, deleteRole, getRoleList, updateRole} from "@/api/role.ts";
import {Plus} from "@element-plus/icons-vue";
import {RoleData} from "@/type/RoleData.ts";
import {ElMessage} from "element-plus";

const tableData = ref([])

const editAddRoleFlag = ref(false)
const isEdit = ref(false)
const roleForm = ref({
  roleId: 0,
  roleName: ''
}as RoleData)


onMounted(() => {
  initData()
})


const initData = () => {
  getRoleList().then(res => {
    tableData.value = res.data
  })
}

const openDialog = (flag: boolean, row?: RoleData) => {

  isEdit.value = flag
  if (isEdit.value){
    roleForm.value.roleId = row?.roleId || 0
    roleForm.value.roleName = row?.roleName || ''
  }

  editAddRoleFlag.value = true
}

const handleDialogSubmit = () => {

  if (isEdit) {

    isEdit.value = false

    handleEdit(roleForm.value)
  }else handleAdd(roleForm.value)

  editAddRoleFlag.value = false

}

const handleAdd = (role: RoleData) => {

  addRole(role).then(_ => {
    initData()
    ElMessage.success('Operate success')
  })
}

const handleEdit = (role: RoleData) => {

  updateRole(role).then(_ => {
    initData()
    ElMessage.success('Operate success')
  })
}

const handleRemove = (roleId: number) => {

  deleteRole(roleId).then(_ => {
    initData()
    ElMessage.success('Operate success')
  })
}

const resetData = () => {

  roleForm.value.roleId = 0
  roleForm.value.roleName = ''
}
</script>

<style scoped>

</style>